package com.ebt.m.presenter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;

import com.ebt.m.AppContext;
import com.ebt.m.AppInitService;
import com.ebt.m.R;
import com.ebt.m.account.json.ValidateCodeSendRequest;
import com.ebt.m.account.json.ValidateCodeSendResponse;
import com.ebt.m.activity.AuthenticationActivity;
import com.ebt.m.activity.BindPhoneActivity;
import com.ebt.m.activity.LoginActivity;
import com.ebt.m.activity.MainActivity;
import com.ebt.m.commons.buscomponent.listview.BasePresenter;
import com.ebt.m.commons.buscomponent.thirtylogin.ShareBlock;
import com.ebt.m.commons.model.data.Constants;
import com.ebt.m.commons.utils.Logger;
import com.ebt.m.commons.utils.NetUtils;
import com.ebt.m.commons.utils.PrefKit;
import com.ebt.m.commons.utils.RxUtil;
import com.ebt.m.customer.service.FetchNetCustomerService;
import com.ebt.m.customer.util.ToastUtil;
import com.ebt.m.data.bean.UserInfo;
import com.ebt.m.data.middle.EBTGetAdviceInfo;
import com.ebt.m.data.rxModel.api.EBTAPI;
import com.ebt.m.data.rxModel.apibean.LoginParam;
import com.ebt.m.data.rxModel.apibean.QuickLoginParam;
import com.ebt.m.data.rxModel.apibean.ThirtyLoginParam;
import com.ebt.m.jpush.JPushUtil;
import com.ebt.m.jpush.PushToken;
import com.ebt.m.jpush.PushTokenResult;
import com.ebt.m.utils.ConfigData;
import com.ebt.m.utils.TalkingDataUtil;
import com.ebt.m.utils.android.EBTUserInfoHelper;
import com.tendcloud.tenddata.TCAgent;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class LoginPresenter extends BasePresenter<LoginContract.IView> implements LoginContract.IPresenter {

    public LoginPresenter(Activity context, LoginContract.IView iView) {
        super(context, iView);
        ShareBlock.getInstance().initWechat(ConfigData.WECHAT_APPID, ConfigData.WECHAT_SECRET);
        ShareBlock.getInstance().initWeibo(ConfigData.WEIBO_APPID);
        ShareBlock.getInstance().initWeiboRedriectUrl(ConfigData.WEIBO_REDRIECT_URL);
        ShareBlock.getInstance().initQQ(ConfigData.QQ_APPID);
    }

    @Override
    public void login(String username, String password) {
        if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) {
            iView.showTip(mContext.getResources().getString(R.string.user_pass_not_null));
            return;
        }
        if (NetUtils.isNetworkConnected(mContext)) {
            iView.showProgress(true);
            loginAction(username, password);
        } else {
            iView.showTip(mContext.getResources().getString(R.string.network_fail));
        }
    }

    private void loginAction(String username, String password) {
        EBTAPI userApi = AppInitService.getEbtApi();
        userApi.getLoginToken(createLoginParams(username, password))
                .compose(RxUtil.rxTransformer(iView))
                .subscribe(dataResult -> {
                    UserInfo userInfo = dataResult.getData();
                    iView.showProgress(false);
                    userInfo.setUserName(username);
                    userInfo.setPassword(password);
                    checkAndHandleLogin(mContext, userInfo);
                }, throwable -> {
                    TalkingDataUtil.onEventWithLabel(TalkingDataUtil.TYPE_LOGIN, "fail");
                    NetUtils.checkHttpException(mContext, throwable);
                    iView.showProgress(false);
                });
    }

    private LoginParam createLoginParams(String username, String password) {
        LoginParam userBean = new LoginParam();
        userBean.password = password;
        userBean.userName = username;
        userBean.requestDevice = ConfigData.REQUEST_DEVICE + "-" + EBTGetAdviceInfo.getMetadata(AppContext.getInstance(), "TD_CHANNEL_ID");
        return userBean;
    }

    /**
     * 获取推送token
     *
     * @param agentId
     */
    private static void createPushToken(int agentId) {
        AppInitService.getEbtApi().createPushToken(createPushTokenParams(agentId))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(data -> {
                    if (data != null && data.getData() != null) {
                        PushTokenResult tokenResult = data.getData();
                        if (!TextUtils.isEmpty(tokenResult.pushToken)) {
                            JPushUtil.setAlisAndTagsWhenLogin(AppContext.getInstance(), tokenResult.pushToken);
                        }
                    }
                }, throwable -> Logger.e(throwable.getMessage()));
    }

    private static PushToken createPushTokenParams(int agentId) {
        PushToken pushToken = new PushToken();
        pushToken.setPushPlatform("JPush");
        pushToken.setApp_id("zyj");
        pushToken.setApp_os("Android_" + EBTGetAdviceInfo.getOSVersion());
        pushToken.setApp_version(EBTGetAdviceInfo.getVersionName());
        pushToken.setApp_version_name(EBTGetAdviceInfo.getVersionName());
        pushToken.setAgentId(agentId);
        pushToken.setDeviceId(PrefKit.getString(AppContext.getInstance(), Constants.DEVICEID_KEY));
        return pushToken;
    }

    public static void checkAndHandleLogin(Context context, UserInfo userInfo) {
        Log.e("isRegisterCompany",String.valueOf(userInfo.isRegisterCompany()));
        if (userInfo.isRegisterCompany()) {
            Intent intent = new Intent(context, MainActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            context.startActivity(intent);
        } else {
            Intent intent = new Intent(context, AuthenticationActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            context.startActivity(intent);
        }
        handleLoginSuccessful(context, userInfo);
    }

    /**
     * 登录成功以后的后续处理
     */
    public static void handleLoginSuccessful(Context context, UserInfo userInfo) {
        TalkingDataUtil.onEventWithLabel(TalkingDataUtil.TYPE_LOGIN, "success");
        PrefKit.writeString(AppContext.getInstance(), ConfigData.SHAREDPREFERENCES_LAST_LOGIN_ACCOUNT, userInfo.getUserName());
        AppContext.setCurrentUser(userInfo);
        //保存到本地
        EBTUserInfoHelper.saveUserKEY(userInfo);
        //创建推送
        createPushToken(userInfo.getUserId());
        //同步客户
        FetchNetCustomerService.startThis(context);
        Map kv = new HashMap();
        if (userInfo != null) {
            kv.put("agentId", String.valueOf(userInfo.getUserId()));
            kv.put("account", userInfo.getUserName());
        }
        //移动应用分析--增加Label、事件参数，对事件做更为详细的追踪时，调用以下方法
        TCAgent.onEvent(AppContext.getInstance(), "login_success", "", kv);
    }

    @Override
    public void sendVerificationCode(String phoneNo) {
        EBTAPI ebtapi = AppInitService.getEbtApi();
        ValidateCodeSendRequest verificationParam = new ValidateCodeSendRequest(phoneNo);
        ebtapi.sendValidateCode(verificationParam)
                .compose(RxUtil.rxTransformer(iView))
                .subscribe(dataResult -> {
                    ValidateCodeSendResponse data = dataResult.getData();
                    if (data != null && data.isSuccess) {
                        iView.showTip(ToastUtil.getSendVCodeSuccessfullyMessage());
                        data.phone = phoneNo;
                        iView.updateVerificationCode(data);
                        iView.showProgress(false);
                    } else {
                        iView.updateVerificationCode(null);
                        iView.showTip(ToastUtil.getSendVCodeErrorMessage(dataResult));
                        iView.showProgress(false);
                    }
                }, throwable -> {
                    NetUtils.checkHttpException(mContext, throwable);
                    iView.showProgress(false);
                });
    }

    @Override
    public void quickLogin(String validateId, String phoneNo, String validateCode) {
        EBTAPI ebtapi = AppInitService.getEbtApi();
        QuickLoginParam loginParam = new QuickLoginParam();
        loginParam.phone = phoneNo;
        loginParam.validateCode = validateCode;
        loginParam.validateId = validateId;
        iView.showProgress(true);
        ebtapi.quickLogin(loginParam)
                .compose(RxUtil.rxTransformer(iView))
                .subscribe(dataResult -> {
                    UserInfo userInfo = dataResult.getData();
                    iView.showProgress(false);
                    userInfo.setUserName(phoneNo);
                    userInfo.setPassword("");
                    checkAndHandleLogin(mContext, userInfo);
                }, throwable -> {
                    TalkingDataUtil.onEventWithLabel(TalkingDataUtil.TYPE_LOGIN, "fail");
                    NetUtils.checkHttpException(mContext, throwable);
                    iView.showProgress(false);
                });

    }

    @Override
    public void thirtyPartLogin(String thirtyId, String thiryType, String userName, String imageUrl) {
        iView.showProgress(true);
        EBTAPI userApi = AppInitService.getEbtApi();
        Observable.just(Arrays.asList(thirtyId, thiryType, userName, imageUrl))
                .flatMap(lists -> userApi.getThirtyLogin(getThirtyLoginParam(lists.get(0), lists.get(1), lists.get(2), lists.get(3))))
                .compose(RxUtil.rxTransformer(iView))
                .subscribe(dataResult -> {
                    UserInfo userInfo = dataResult.getData();
                    iView.showProgress(false);
                    userInfo.setUserName(userName);
                    userInfo.setPassword("");
                    //1.如果phone为空，跳转到绑定手机号界面
                    if (TextUtils.isEmpty(userInfo.getPhone())) {
                        Intent it = new Intent(mContext, BindPhoneActivity.class);
                        it.putExtra(BindPhoneActivity.MODE, BindPhoneActivity.MODE_BIND);
                        it.putExtra(BindPhoneActivity.FROM, LoginPresenter.class.getCanonicalName());
                        it.putExtra(BindPhoneActivity.ThirdParty.THIRD_PARTY_ID, thirtyId);
                        it.putExtra(BindPhoneActivity.ThirdParty.THIRD_PARTY_TYPE, thiryType);
                        it.putExtra(BindPhoneActivity.ThirdParty.THIRD_PARTY_USER_NAME, userName);
                        it.putExtra(BindPhoneActivity.ThirdParty.THIRD_PARTY_IMAGE_URL, imageUrl);
                        it.putExtra(BindPhoneActivity.ThirdParty.THIRD_PARTY_TOKEN, userInfo.getAccessToken());
                        mContext.startActivity(it);
                    } else {
                        //2. 直接登录
                        checkAndHandleLogin(mContext, userInfo);
                    }
                    ((LoginActivity) mContext).finish();
                }, throwable -> {
                    NetUtils.checkHttpException(mContext, throwable);
                    iView.showProgress(false);
                });

    }

    private ThirtyLoginParam getThirtyLoginParam(String thirtyId, String thiryType, String userName, String imageUrl) {
        ThirtyLoginParam loginParam = new ThirtyLoginParam();
        loginParam.UserName = thirtyId;
        loginParam.ReqestDevice = ConfigData.REQUEST_DEVICE + "-" + EBTGetAdviceInfo.getMetadata(AppContext.getInstance(), "TD_CHANNEL_ID");
        loginParam.APKVersion = EBTGetAdviceInfo.getAppVersionName();
        loginParam.CardName = userName;
        loginParam.BindType = thiryType;
        loginParam.PortraitAddress = imageUrl;
        loginParam.CreateBy = ConfigData.REQUEST_DEVICE + "-" + EBTGetAdviceInfo.getMetadata(AppContext.getInstance(), "TD_CHANNEL_ID");
        loginParam.model = Build.MODEL;
        loginParam.Mac = EBTGetAdviceInfo.getMacAddress();
        loginParam.DeviceSN = EBTGetAdviceInfo.getDeviceId();
        return loginParam;
    }

}
